package drds.plus.executor.function.scalar.datatime;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;
import drds.plus.sql_process.type.impl.IntervalType;

import java.util.Calendar;

public class DateSub extends ScalarFunction {

    public Object compute(ExecuteContext executeContext, Object[] args) {
        for (Object arg : args) {
            if (Utils.isNull(arg)) {
                return null;
            }
        }

        java.sql.Timestamp timestamp = Type.TimestampType.convert(args[0]);
        Calendar cal = Calendar.getInstance();
        cal.setTime(timestamp);

        Object day = args[1];
        if (day instanceof IntervalType) {
            ((IntervalType) day).process(cal, -1);
        } else {
            cal.add(Calendar.DAY_OF_YEAR, Type.IntegerType.convert(day));
        }

        Type type = getReturnType();
        return type.convert(cal);
    }

    public Type getReturnType() {
        return getFirstArgType();
    }

    public String[] getFunctionNames() {
        return new String[]{"DATE_SUB", "SUBDATE"};
    }
}
